import { app, shell, BrowserWindow, screen, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import WebSocket from 'ws'
import axios from 'axios'
import fs from 'fs'
let mainWindow
function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: screen.getPrimaryDisplay().size.width,
    height: screen.getPrimaryDisplay().size.height,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
  mainWindow.maximize()
}
class ReconnectingWebSocket {
  constructor(url, options = {}) {
    this.url = url
    this.options = options
    this.reconnectInterval = options.reconnectInterval || 5000
    this.maxRetries = options.maxRetries || Infinity
    this.retryCount = 0
    this.isConnecting = false
    this.ws = null

    this.connect()
  }
  connect() {
    if (this.isConnecting) return
    this.isConnecting = true

    this.ws = new WebSocket(this.url)
    this.ws.on('open', () => {
      console.log('client ws open')
      this.isConnecting = false
      this.retryCount = 0 //重置连接次数
    })
    this.ws.onmessage = (e) => {
      // 去掉字符串两边的"
      let year = e.data.replace(/"/g, '') || 2014
      let url = 'http://192.168.30.13:8080/getyeardata?name=' + year
      axios
        .get(url)
        .then((res) => {
          console.log('axios got data', res.data[0])
          mainWindow.webContents.send('data-change', {
            message: 'data from main process',
            data: res.data[0]
          })
        })
        .catch((err) => {
          console.log(err)
        })
    }
    this.ws.onclose = () => {
      console.log('websocket closed')
      this.isConnecting = false
      if (this.retryCount < this.maxRetries) {
        setTimeout(() => {
          this.retryCount++
          this.connect()
        }, this.reconnectInterval)
      } else {
        console.log('Max retry attempts reached, giving up.')
      }
    }
    this.ws.onerror = (err) => {
      console.log('ws error: ', err)
    }
  }
}
// websocket 实例
let ws_instance = null

function createWSServer(){
  let url = ''
  fs.readFile(join(__dirname, '../../resources/base_config.json'),  (err, data) => {
    if(err) return console.error('ws_error', err)
    url = 'ws://' + JSON.parse(data).ws_server_ip + ':' + JSON.parse(data).ws_server_port
    if (ws_instance != null) {
      ws_instance = null
    } else {
      ws_instance = new ReconnectingWebSocket(url, {})
    }
  })
}
function getWSserverSettings(){
  fs.readFile(join(__dirname, '../../resources/base_config.json'), (err, data) => {
    if(err) return console.error('ws_error', err)
    mainWindow.webContents.send('send_ws_config', JSON.parse(data))
  })
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  ipcMain.on('get_wsserver_config',() => {
    getWSserverSettings()
  })
  ipcMain.on('set_wsserver_config',(event, data) => {
    fs.writeFile(join(__dirname, '../../resources/base_config.json'), data, (err) => {
      if (err) {
        console.log('error when set wsserver')
      }
      console.log('success in set wsserver')
      createWSServer()
    })
  })
  createWindow()

  createWSServer()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
